package com.app.utils.util;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 字符串操作工具包
 *
 * @author xuxinghai
 * @version 1.0
 * @created 2016-7-12
 */
public class StringUtils {
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static String PATTERN_CHAR_NUM_EN = "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$";//数字/汉字/英文的正则

    /**
     * 判断给定字符串是否空白串。 空白串是指由空
     * 格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            if(TextUtils.isEmpty(str)){
                return  defValue;
            }
            return Integer.parseInt(str.trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defValue;
    }

    /**
     * 字符串转float
     * @param str
     * @param defValue
     * @return
     */
    public static float toFloat(String str, float defValue) {
        try {
            if(TextUtils.isEmpty(str)){
                return  defValue;
            }

            return Float.parseFloat(str.trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defValue;
    }


    /**
     *
     * 字符串转整数
     *
     * @param str
     * @return 转换异常返回 0
     */
    public static long toLong(String str,long defValue) {
        try {
            if(TextUtils.isEmpty(str)){
                return  defValue;
            }
            return Long.parseLong(str.trim());
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * HTML化字符串
     *
     * @param str
     * @return
     */
    public static Spanned fromHtml(String str) {
        if (!isEmpty(str)) {
            return Html.fromHtml(Html.fromHtml(str).toString());
        } else
            return Html.fromHtml("没有描述");
    }


    /**
     * 对字符串进行Des加密，将字符串转化为字节数组解密
     */
    public static String desCrypto(byte[] datasource, String password) {

        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            // 现在，获取数据并加密
            // 正式执行加密操作

            return Base64.encodeToString(cipher.doFinal(datasource),
                    Base64.DEFAULT);
        } catch (Throwable e) {
            return null;
        }
    }

    /**
     * 将加密的密文字节数组转化为明文字节数组
     */
    public static String decrypt(byte[] src, String password) throws Exception {

        byte[] decordedValue = Base64.decode(src, Base64.DEFAULT);
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return new String(cipher.doFinal(decordedValue));
    }

    /**
     * 使用 md5 加密
     *
     * @param string
     * @return
     */
    public static String md5(String string) {
        if(TextUtils.isEmpty(string)){
            return "";
        }
        byte[] hash = null;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (Exception e) {
//            throw new RuntimeException("没有md5这个算法！");
        }
        if (hash != null) {
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (int i = 0; i < hash.length; i++) {
                //0xFF 表示 255
                if ((hash[i] & 0xFF) < 0x10){
                    hex.append("0");
                }
                hex.append(Integer.toHexString(hash[i] & 0xFF));
            }
            return hex.toString();
        } else {
            return "";
        }
        // 另一种加密方法
        // try {
        // MessageDigest bmd5 = MessageDigest.getInstance("MD5");
        // bmd5.update(string.getBytes());
        // int i;
        // StringBuffer buf = new StringBuffer();
        // byte[] b = bmd5.digest();
        // for (int offset = 0; offset < b.length; offset++) {
        // i = b[offset];
        // if (i < 0)
        // i += 256;
        // if (i < 16)
        // buf.append("0");
        // buf.append(Integer.toHexString(i));
        // }
        // StringUtils.log(buf.toString());
        // return buf.toString();
        // } catch (NoSuchAlgorithmException e) {
        // e.printStackTrace();
        // }
        // return "";
    }

    /**
     * 另一种md5的转化法则
     * @param plainText
     * @return
     */
    public static String md5_method1(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    /**
     * base64加密
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        if(TextUtils.isEmpty(str)){
            return str;
        }
        byte[] b = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        String ss = Base64.encodeToString(b, Base64.DEFAULT);
        String ss = Base64.encodeToString(b, Base64.NO_WRAP);
        return ss;
    }


    /**
     * 检查字符串是否只支持数字汉子和英文
     * @param str
     * @return
     */
    public static boolean checkNickName(String str){
        Pattern pattern = Pattern.compile(PATTERN_CHAR_NUM_EN);
        Matcher matcher = pattern.matcher(str);
        boolean match = matcher.matches();

        return match;
    }


    /**
     * 匹配正常的url(去除url的参数)
     * @param url
     * @return
     */
    public static String macthUrl(String url){
        if(TextUtils.isEmpty(url)){
            return url;
        }

        if(url.length() > 18){
            String substring = url.substring(0, url.length() - 18);

            return substring;
        }

//        String[] split = url.split("\\?");
//        if(split != null && split.length > 0){
//            Pattern compile = Pattern.compile("^\\d*[1-9]\\d*$");
//            Matcher matcher = compile.matcher(split[split.length - 1]);
//            boolean matches = matcher.matches();
//
//            if(matches){
//
//                String substring = url.substring(0, url.length() - 18);
//
//                return substring;
//            }else{
//                return url;
//            }
//        }
        return url;
    }


}